import datetime
import json

from django.core.files.storage import FileSystemStorage
from django.db import connection, transaction,connections
from django.http import JsonResponse
from django.views import View

from rest_framework_simplejwt.tokens import RefreshToken

from app.utils.MD5 import MD5
from app.utils.OrderNumber import OrderNumber
from app.utils.User import User


# Create your views here.

class UploadAvatarView(View):
    """
     处理⽤户头像上传请求的视图类
    """

    def post(self, request):
        file_obj = request.FILES['avatar']
        userId = request.POST.get('userId')
        # 创建一个文件系统存储实例，指定存储目录为'media/app_userAvatar/'
        fs = FileSystemStorage(location='media/app_userAvatar/')

        # 使用文件系统存储实例保存上传的头像文件
        # 参数 file_obj.name 是上传文件的名称
        # 参数 file_obj 是包含文件内容的文件对象
        # 方法 save 返回文件在服务器上的名称，这通常是在重命名文件或使用哈希值时很有用
        filename = fs.save(file_obj.name, file_obj)

        # 构造保存文件的URL
        # 方法 url 返回文件相对于存储目录的URL路径
        # 在这里，我们将这个路径与服务器的基础URL拼接起来，形成完整的文件访问URL

        print(filename)
        try:
            with connection.cursor() as cursor:
                sql = 'update user set head=%s,update_time=NOW() where id=%s'
                cursor.execute(sql, [filename, userId])
            return JsonResponse({'code': 200, 'msg': '上传成功', 'file_url': filename})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'msg': '上传失败'})


from django.views import View
from django.http import JsonResponse
from django.core.files.storage import FileSystemStorage
from django.db import connection
import json
import datetime


class UploadComment(View):
    def post(self, request):
        # 获取评论信息
        comment_info = request.POST.get("commentInfo")
        try:
            comment_info = json.loads(comment_info)
        except json.JSONDecodeError:
            return JsonResponse({'code': 400, 'msg': '评论信息解析失败'})

        user_id = int(comment_info['userId'])
        content = comment_info['content']
        storeId = int(comment_info['storeId'])
        rate = comment_info['value']

        # 初始化文件存储
        fs = FileSystemStorage(location='media/comment/')
        uploaded_files = []

        # 保存文件到服务器
        for file_key in request.FILES:
            uploaded_file = request.FILES[file_key]
            filename = fs.save(uploaded_file.name, uploaded_file)
            uploaded_files.append(filename)

        try:
            with connection.cursor() as cursor:
                # 插入评论信息
                cursor.execute(
                    'INSERT INTO comments (user_id, store_id, rate, content, create_time) VALUES (%s, %s, %s, %s, %s)',
                    [user_id, storeId, rate, content, datetime.datetime.now()]
                )
                cursor.execute('SELECT id FROM comments WHERE user_id=%s AND store_id=%s', [user_id, 13])
                comment_id = cursor.fetchone()[0]

                # 插入评论图片
                for image in uploaded_files:
                    cursor.execute('INSERT INTO comments_img (comment_id, img_name) VALUES (%s, %s)',
                                   [comment_id, image])

            return JsonResponse({'code': 200, 'msg': '评论成功'})

        except Exception as e:
            return JsonResponse({'code': 500, 'msg': f'评论失败: {str(e)}'})


class LoginView(View):
    def post(self, request):
        # 接受前端传来的用户名和密码
        data = json.loads(request.body)
        print(data)
        username = data['userInfo']['username']
        password = data['userInfo']['password']
        md5 = MD5()
        password = md5.md5_encrypt(password)
        print(username, password)
        try:
            with connection.cursor() as cursor:
                cursor.execute('SELECT * FROM user WHERE username = %s and password=%s', [username, password])
                user = cursor.fetchone()
                print(user)
                if user:
                    cursor.execute('UPDATE user SET update_time=%s WHERE id=%s', [datetime.datetime.now(), user[0]])
                    column_names = ['id', 'head', 'username', 'password', 'email', 'status', 'balance', 'role',
                                    'create_time', 'update_time']  # 根据你的表结构调整字段名
                    # 将查询结果转换为字典
                    print("-------------")
                    user_dict = dict(zip(column_names, user))
                    print(user_dict)
                    user = User(user_dict)
                    refresh_token = RefreshToken.for_user(user)
                    access_token = str(refresh_token.access_token)

                    return JsonResponse(
                        {'code': 200, 'info': '登录成功', 'refresh_token': str(refresh_token),
                         'access_token': access_token,
                         'userInfo': user_dict})
                else:
                    return JsonResponse({'code': 500, 'info': '用户名或者密码错误'})


        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'info': '服务器错误'})


class RegisterView(View):
    def post(self, request):
        data = json.loads(request.body)
        username = data['userInfo']['username']
        password = data['userInfo']['password']
        md5 = MD5()
        password = md5.md5_encrypt(password)
        email = data['userInfo']['email']
        with connection.cursor() as cursor:
            cursor.execute('SELECT * FROM user WHERE email = %s or username=%s', [email, username])
            user = cursor.fetchone()
            if user:
                return JsonResponse({'code': 500, 'info': '账号已存在'})
            else:
                create_date = datetime.datetime.now()
                cursor.execute('INSERT INTO user (username, password, email,create_time) VALUES (%s, %s, %s,%s)',
                               [username, password, email, create_date])
                return JsonResponse({'code': 200, 'info': '注册成功'})


class ShowView(View):
    def get(self, request):
        with connection.cursor() as cursor:
            cursor.execute('SELECT title.title,store.* FROM store,title where title.id=store.title_id')
            data = cursor.fetchall()
            column_names = ['title', 'id', 'img', 'name', 'rate', 'sale', 'price1', 'price2', 'distance']
            data = [dict(zip(column_names, row)) for row in data]
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})


class ShowDishesView(View):
    def get(self, request):
        storeId = request.GET.get("storeId")
        print(id)
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT dishes.* FROM store_dishes,dishes WHERE store_dishes.dishes_id = dishes.id and store_dishes.store_id = %s',
                [storeId])
            data = cursor.fetchall()

            column_names = ['id', 'name', 'img', 'price', 'quantity', 'num']
            data = [dict(zip(column_names, row)) for row in data]
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})


class ShowStoreView(View):
    def get(self, request):
        storeId = request.GET.get("storeId")
        print(id)
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT title.title,store.* FROM store,title WHERE store.title_id = title.id and store.id = %s',
                [storeId])
            data = cursor.fetchone()
            column_names = ['title', 'id', 'img', 'name', 'rate', 'sale', 'price1', 'price2', 'distance']
            data = dict(zip(column_names, data))
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})


class GetUserInfo(View):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        print(userId)
        with connection.cursor() as cursor:
            cursor.execute('SELECT * FROM user WHERE id = %s', [userId])
            data = cursor.fetchone()
            column_names = ['id', 'head', 'username', 'password', 'email', 'status', 'balance', 'role', 'create_time',
                            'update_time']
            data = dict(zip(column_names, data))
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'userInfo': data})


class AddShopCar(View):
    def get(self, request):
        id = request.GET.get("id")
        num = request.GET.get("num")
        userId = request.GET.get("userId")
        print(id, num, userId)
        try:
            with transaction.atomic():
                with connection.cursor() as cursor:
                    result = cursor.execute(
                        'SELECT * FROM shopcar WHERE user_id = %s and dishes_id = %s and is_delete =1', [userId, id])
                    print(cursor.fetchone())
                    if not result:
                        print('添加新商品')
                        cursor.execute("INSERT INTO shopcar(dishes_id,goods_num,user_id) VALUES(%s,%s,%s)",
                                       [id, num, userId])
                        cursor.execute("Update dishes set quantity=quantity-%s WHERE id = %s", [num, id])
                        return JsonResponse({'code': 200, 'info': '添加成功'})
                    cursor.execute(
                        "UPDATE shopcar SET goods_num = goods_num + %s WHERE user_id = %s and dishes_id = %s",
                        [num, userId, id])
                    cursor.execute("Update dishes set quantity=quantity-%s WHERE id = %s", [num, id])
                    return JsonResponse({'code': 200, 'info': '添加成功'})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'info': '添加失败'})


class ShopCar(View):
    def get(self, request):
        userId = request.GET.get("userId")
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT shopcar.id, shopcar.dishes_id,shopcar.user_id,shopcar.goods_num,dishes.price,dishes.name,dishes.img FROM shopcar,dishes WHERE shopcar.dishes_id = dishes.id and shopcar.user_id = %s and is_delete=1',
                [userId])
            data = cursor.fetchall()
            column_names = ['id', 'dishes_id', 'userId', 'goods_num', 'price', 'name', 'img']
            data = [dict(zip(column_names, row)) for row in data]
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})


class DeleteShopCar(View):
    def delete(self, request):
        userId = request.GET.get("userId")
        dishesId = request.GET.get("dishes_id")
        goods_num = request.GET.get("goods_num")
        print(userId, dishesId, goods_num)
        if (dishesId):
            with connection.cursor() as cursor:
                cursor.execute("update shopcar set is_delete=-1 where user_id=%s and dishes_id=%s", [userId, dishesId])
                cursor.execute("Update dishes set quantity=quantity+%s WHERE id = %s", [goods_num, dishesId])
                cursor.execute(
                    "SELECT shopcar.id,shopcar.dishes_id,shopcar.goods_num,dishes.price,dishes.name,dishes.img FROM shopcar,dishes WHERE shopcar.dishes_id = dishes.id and shopcar.user_id = %s and is_delete=1",
                    [userId])
                data = cursor.fetchall()
                column_names = ['id', 'dishes_id', 'goods_num', 'price', 'name', 'img']
                data = [dict(zip(column_names, row)) for row in data]
                return JsonResponse({'code': 200, 'info': '删除成功', 'data': data})
        else:
            return JsonResponse({'code': 500, 'info': '删除失败'})


class AddBalance(View):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        with connection.cursor() as cursor:
            cursor.execute("UPDATE user SET balance = balance + 10000 WHERE id = %s", [userId])
            return JsonResponse({'code': 200, 'info': '充值成功'})


class AddressView(View):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        print(userId)
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT address.id,address.consignee,address.tel,address.detail_address FROM address WHERE address.user_id=%s',
                [userId])
            data = cursor.fetchall()
            print(data)
            column_names = ['id', 'name', 'tel', 'address']
            data = [dict(zip(column_names, row)) for row in data]
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})


class LoadAddress(View):
    def get(self, request):
        address_id = request.GET.get("address_id")
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT address.id,address.consignee,address.tel,address.detail_address FROM address WHERE address.id=%s',
                [address_id])
            data = cursor.fetchone()
            column_names = ['id', 'name', 'tel', 'address']
            data = dict(zip(column_names, data))
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})


class ChangeAddress(View):
    def put(self, request):
        data = json.loads(request.body)
        address_id = data['address_id']
        name = data['name']
        tel = data['tel']
        address = data['address']
        print(address_id, name, tel, address)
        with connection.cursor() as cursor:
            cursor.execute(
                'UPDATE address SET consignee=%s,tel=%s,detail_address=%s WHERE id=%s',
                [name, tel, address, address_id])
            return JsonResponse({'code': 200, 'info': '修改成功'})


class AddAddress(View):
    def post(self, request):
        data = json.loads(request.body)
        print(data)
        user_id = data['user_id']
        name = data['name']
        tel = data['tel']
        address = data['address']
        print(user_id, name, tel, address)
        with connection.cursor() as cursor:
            cursor.execute(
                'INSERT INTO address(user_id,consignee,tel,detail_address) VALUES(%s,%s,%s,%s)',
                [user_id, name, tel, address])
            return JsonResponse({'code': 200, 'info': '添加成功'})


class AddOrder(View):
    def put(self, request):
        data = json.loads(request.body)
        list = data['list']
        print(data)
        addressId = data['addressId']
        totalPrice = int(data['totalPrice'])
        try:
            with transaction.atomic():
                with connection.cursor() as cursor:
                    for index, item in enumerate(list):
                        id = item['id']
                        userId = item['userId']
                        if (index == 0):
                            orderNumber = OrderNumber().generate_order_number()
                            print(orderNumber)
                            cursor.execute(
                                'insert into `order`(order_number,totalPrice,address_id,user_id,order_time) values (%s,%s,%s,%s,%s)',
                                [orderNumber, totalPrice, addressId, userId, datetime.datetime.now()])
                            cursor.execute('select id from `order` where order_number=%s', [orderNumber])
                            orderId = cursor.fetchone()[0]
                        cursor.execute('insert into order_shopcar(order_id,shopcar_id) values (%s,%s)', [orderId, id])
                        cursor.execute('update shopcar set is_delete=%s where id=%s', [0, id])
                    return JsonResponse({'code': 200, 'info': '订单生成成功', 'orderNumber': orderNumber})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'info': '订单生成失败'})


class GetOrder(View):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        with connection.cursor() as cursor:
            cursor.execute(
                'SELECT `order`.id,`order`.order_number,`order`.totalPrice,`order`.address_id,`order`.order_time,shopcar.goods_num,dishes.price,dishes.name,dishes.img,order_status.status,`order`.status '
                'FROM `order`,shopcar,dishes,`address`,order_shopcar,order_status '
                'WHERE `order`.id = order_shopcar.order_id and order_shopcar.shopcar_id=shopcar.id '
                'and shopcar.dishes_id = dishes.id and `address`.id = `order`.address_id and order_status.order_status = `order`.status and `order`.user_id =%s',
                [userId])
            data = cursor.fetchall()
            column_names = ['id', 'order_number', 'totalPrice', 'address_id', 'order_time', 'goods_num', 'price',
                            'name', 'img', 'status', 'sta']
            data = [dict(zip(column_names, row)) for row in data]
            print(data)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})

class Pay(View):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        totalPrice = data['totalPrice']
        orderNumber = data['orderNumber']
        try:
            with transaction.atomic():
                with connection.cursor() as cursor:
                    cursor.execute('update user set balance=balance-%s where id=%s', [totalPrice, userId])
                    cursor.execute('update `order` set status=1 where order_number=%s', [orderNumber])
                    return JsonResponse({'code': 200, 'info': '支付成功'})
        except Exception as e:
            return JsonResponse({'code': 400, 'info': '支付失败'})


class ShowStarStore(View):
    def get(self, request):
        userId = request.GET.get('userId')
        storeId = request.GET.get('storeId')
        print(userId, storeId)
        with connection.cursor() as cursor:
            cursor.execute('select * from user_store where user_id=%s and store_id=%s', [userId, storeId])
            if cursor.fetchone():
                return JsonResponse({'code': 200, 'info': '查询成功', 'star': 1})
            else:
                return JsonResponse({'code': 200, 'info': '查询成功', 'star': 0})

    def put(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        star = data['star']
        storeId = data['storeId']
        print(userId, star, storeId)
        with connection.cursor() as cursor:
            if star == 1:
                cursor.execute('delete from user_store where user_id=%s and store_id=%s', [userId, storeId])
                return JsonResponse({'code': 200, 'info': '取消收藏成功', 'star': 0})
            else:
                cursor.execute('insert into user_store(user_id,store_id) values (%s,%s)', [userId, storeId])
                return JsonResponse({'code': 200, 'info': '收藏成功', 'star': 1})


class LoadStarStore(View):
    def get(self, request):
        userId = request.GET.get('userId')
        print(userId)
        with connection.cursor() as cursor:
            cursor.execute("select store_id from user_store where user_id=%s", [userId])
            data = cursor.fetchall()
            list = []
            for index, item in enumerate(data):
                cursor.execute('select id,img,name,rate,sale,price1,price2,distance from store where id=%s', [item[0]])
                column_names = ['id', 'img', 'name', 'rate', 'sale', 'price1', 'price2', 'distance']
                list.append(dict(zip(column_names, cursor.fetchone())))
            print(list)
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': list})


class CancelOrder(View):
    def post(self, request):
        data = json.loads(request.body)
        orderId = data['orderId']
        userId = data['userId']
        totalPrice = data['totalPrice']
        try:
            with transaction.atomic():
                with connection.cursor() as cursor:
                    # cursor.execute('update `order` set is_delete=-1 where id=%s',[orderId])
                    cursor.execute('update user set balance=balance+%s where id=%s', [totalPrice, userId])
                    return JsonResponse({'code': 200, 'info': '取消订单'})
        except Exception as e:
            return JsonResponse({'code': 400, 'info': '取消订单失败'})

class GetStoreId(View):
    def get(self, request):
        orderId = int(request.GET.get('orderId'))
        print(orderId,type(orderId))
        with connection.cursor() as cursor:
            cursor.execute('SELECT store.id FROM `order` JOIN order_shopcar ON `order`.id = order_shopcar.order_id JOIN shopcar ON order_shopcar.shopcar_id = shopcar.id JOIN store_dishes ON shopcar.dishes_id = store_dishes.dishes_id JOIN store ON store.id = store_dishes.store_id WHERE `order`.id = %s',[orderId])
            data = cursor.fetchone()
            print(data)
            if data:
                return JsonResponse({'code': 200, 'info': '查询成功', 'storeId': data[0]})
            else:
                return JsonResponse({'code': 400, 'info': '查询失败'})
class UpdateOrderStatus(View):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        orderId = data['orderId']
        status = data['status']
        with connection.cursor() as cursor:
            if status == 1:
                cursor.execute('update `order` set status=2 where id=%s and user_id=%s', [orderId,userId])
            else:
                cursor.execute('update `order` set status=-1 where id=%s and user_id=%s', [orderId,userId])
            return JsonResponse({'code': 200, 'info': '订单状态更新成功'})


# class ShowStarDishes(View):
#     def get(self,request):
#         userId = request.GET.get('userId')
#         storeId = request.GET.get('storeId')
#         with connection.cursor() as cursor:
#             cursor.execute('select * from user_dishes where user_id=%s and dishes_id=%s', [userId,storeId])
#             if cursor.fetchone():
#                 return JsonResponse({'code': 200, 'info': '查询成功', 'star':1})
#             else:
#                 return JsonResponse({'code': 200, 'info': '查询成功', 'star':0})
#     def put(self,request):
#         data = json.loads(request.body)
#         userId = data['userId']
#         star = data['star']
#         storeId = data['storeId']
#         print(userId,star,storeId)
#         with connection.cursor() as cursor:
#             if star==1:
#                 cursor.execute('delete from user_dishes where user_id=%s and dishes_id=%s', [userId,storeId])
#                 return JsonResponse({'code': 200, 'info': '取消收藏成功', 'star':0})
#             else:
#                 cursor.execute('insert into user_dishes(user_id,dishes_id) values (%s,%s)', [userId,storeId])
#                 return JsonResponse({'code': 200, 'info': '收藏成功', 'star':1})
#
# class LoadStarDishes(View):
#     def get(self,request):
#         userId = request.GET.get('userId')
#         storeId = request.GET.get('storeId')
#         with connection.cursor() as cursor:
#             cursor.execute("select dishes_id from store_dishes where store_id=%s", [storeId])
#             data = cursor.fetchall()
#             print(data)
#             for index,item in enumerate(data):
#                 cursor.execute('select id,img,name,rate,sale,price1,price2,distance from store where id=%s', [item[0]])
#                 column_names = ['id', 'img', 'name', 'rate', 'sale', 'price1', 'price2', 'distance']
#             print(list)
#             return JsonResponse({'code': 200, 'info': '查询成功', 'data': list})

# class StoreListView(View):
#     def get(self, request):
#         store_data = []
#         with connection.cursor() as cursor:
#             cursor.execute("""
#                 SELECT s.id as store_id, s.name, t.title, d.id as dish_id, d.name as dish_name, d.img as dish_src, d.price
#                 FROM store s
#                 LEFT JOIN store_dishes sd ON s.id = sd.store_id
#                 LEFT JOIN dishes d ON sd.dishes_id = d.id
#                 LEFT JOIN title t on s.title_id = t.id
#             """)
#             stores = cursor.fetchall()
#
#         for store in stores:
#             store_dict = {
#                 'store_id': store[0],  # 店铺 ID
#                 'name': store[1],
#                 'type': store[2],
#                 'products': []
#             }
#             if store[0] == store_data[-1]['store_id'] if store_data else None:
#                 store_data[-1]['products'].append({
#                     'dish_id': store[3],  # 菜品 ID
#                     'name': store[4],
#                     'img': store[5],
#                     'details': {
#                         'price': store[6],
#                     }
#                 })
#             else:
#                 store_data.append(store_dict)
#                 store_data[-1]['products'].append({
#                     'dish_id': store[3],  # 菜品 ID
#                     'name': store[4],
#                     'img': store[5],
#                     'details': {
#                         'price': store[6],
#                     }
#                 })
#
#         return JsonResponse(store_data, safe=False)
#
#
# # views.py
# class SearchProductsView(View):
#     def get(self, request):
#         query = request.GET.get('query')
#         if query:
#             with connection.cursor() as cursor:
#                 cursor.execute("""
#                     SELECT s.id as store_id, s.name as store_name,t.title, d.id, d.name, d.img, d.price
#                     FROM dishes d
#                     JOIN store_dishes sd ON d.id = sd.dishes_id
#                     JOIN store s ON sd.store_id = s.id
#                     JOIN title t ON t.id = s.title_id
#                     WHERE d.name LIKE %s
#                 """, [f'%{query}%'])
#                 products = cursor.fetchall()
#
#             product_data = []
#             for product in products:
#                 product_dict = {
#                     'store_id': product[0],  # 店铺 ID
#                     'store_name': product[1],
#                     'store_type': product[2],  # 店铺类型
#                     'id': product[3],
#                     'name': product[4],
#                     'img': product[5],
#                     'details': {
#                         'price': product[6],
#                         'specs': product[7],
#                     }
#                 }
#                 product_data.append(product_dict)
#             return JsonResponse(product_data, safe=False)
#         else:
#             return JsonResponse([], safe=False)

class StoreListView(View):
    def get(self, request):
        store_data = []
        with connections['default'].cursor() as cursor:
            cursor.execute("""
                SELECT s.id as store_id, s.name, t.title as type, d.id as dish_id, d.name as dish_name, d.img as dish_src, d.price
                FROM store s
                LEFT JOIN store_dishes sd ON s.id = sd.store_id
                LEFT JOIN dishes d ON sd.dishes_id = d.id
                LEFT JOIN title t ON s.title_id = t.id
            """)
            stores = cursor.fetchall()

        for store in stores:
            store_dict = {
                'store_id': store[0],  # 店铺 ID
                'name': store[1],
                'type': store[2],  # 从 title 表中获取的 type
                'products': []
            }
            if store_data and store[0] == store_data[-1]['store_id']:
                store_data[-1]['products'].append({
                    'dish_id': store[3],  # 菜品 ID
                    'name': store[4],
                    'img': store[5],
                    'details': {
                        'price': store[6],
                    }
                })
            else:
                store_data.append(store_dict)
                store_data[-1]['products'].append({
                    'dish_id': store[3],  # 菜品 ID
                    'name': store[4],
                    'img': store[5],
                    'details': {
                        'price': store[6],
                    }
                })

        return JsonResponse(store_data, safe=False)
# views.py
class SearchProductsView(View):
    def get(self, request):
        query = request.GET.get('query')
        if query:
            with connections['default'].cursor() as cursor:
                cursor.execute("""
                    SELECT s.id as store_id, s.name as store_name, t.title as store_type, d.id, d.name, d.img, d.price
                    FROM dishes d
                    JOIN store_dishes sd ON d.id = sd.dishes_id
                    JOIN store s ON sd.store_id = s.id
                    JOIN title t ON s.title_id = t.id
                    WHERE d.name LIKE %s
                """, [f'%{query}%'])
                products = cursor.fetchall()

            product_data = []
            for product in products:
                product_dict = {
                    'store_id': product[0],  # 店铺 ID
                    'store_name': product[1],
                    'store_type': product[2],  # 从 title 表中获取的 type
                    'id': product[3],
                    'name': product[4],
                    'img': product[5],
                    'details': {
                        'price': product[6],
                    }
                }
                product_data.append(product_dict)
            return JsonResponse(product_data, safe=False)
        else:
            return JsonResponse([], safe=False)
